<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <link href="../../component/layui/css/layui.css" rel="stylesheet" />
    <link href="../../admin/css/pearCommon.css" rel="stylesheet" />
</head>
<body>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <label class="layui-form-label">要素名称</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="demoReload" name="elementName" placeholder="" type="text">
                </div>
                <a class="pear-btn pear-btn-md pear-btn-primary" data-type="reload" id="featureSearch" lay-filter="user-query" lay-submit>
                    <i class="layui-icon layui-icon-search"></i>
                    查询
                </a>
                <button type="button" class="pear-btn pear-btn-md" id="featureReset">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
            </div>
        </form>
    </div>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="user-table" lay-filter="user-table"></table>
    </div>
</div>
</body>
<div class="site-text" style="margin: 5%; display: none" id="service-window"  target="test123">
    <form class="layui-form" id="service-add">
        <div class="layui-form-item">
            <label class="layui-form-label">要素名称</label>
            <div class="layui-input-block">
                <input type="text" id="feature-name" name="title" required  lay-verify="required" placeholder="请输入要素名称" maxlength="50" autocomplete="off" class="layui-input">
                <div class="layui-form-mid layui-word-aux">必填项</div>
            </div>
        </div>
        <div class="layui-form-item" id="service-type">
            <label class="layui-form-label">要素格式</label>
            <div class="layui-input-block">
                <select name="city" id="feature-type" lay-verify="required">
                    <option value=""></option>
                    <option value="1">3dTiles</option>
<!--                    <option value="2">2-geoJson</option>-->
<!--                    <option value="3">3-wms</option>-->
<!--                    <option value="4">4-wfs</option>-->
                    <option value="4">wfs</option>
                </select>
                <div class="layui-form-mid layui-word-aux">必填项</div>
            </div>
        </div>
        <div class="layui-form-item" id="service-address">
            <label class="layui-form-label">服务地址</label>
            <div class="layui-input-block">
                <input type="text" id="feature-address" name="address" required lay-verify="required" placeholder="请输入服务地址" maxlength="200" autocomplete="off" class="layui-input">
                <div class="layui-form-mid layui-word-aux">必填项</div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">要素描述</label>
            <div class="layui-input-block">
                <textarea name="desc" id="feature-detail" placeholder="请输入要素描述" maxlength="200" class="layui-textarea"></textarea>
            </div>
        </div>
    </form>

</div>


<script type="text/html" id="user-toolbar">
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
        <i class="layui-icon layui-icon-add-1"></i>
        添加要素
    </button>
    <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove">
        <i class="layui-icon layui-icon-delete"></i>
        删除
    </button>
</script>

<script type="text/html" id="user-bar">
    <input type="checkbox" name="状态" valueId="{{d.id}}" valueElementName="{{d.elementName}}" valueElementUrl="{{d.elementUrl}}" valueServiceType="{{d.serviceType}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="enabledState" {{ d.status == "1" ? "checked" : "" }}>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">预览</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script id="data-type" type="text/html">
    {{#if (d.serviceType == 1) { }}
    <span>3dTiles</span>
    {{# }else if(d.serviceType == 2){ }}
    <span>geoJson</span>
    {{# }else if(d.serviceType == 3){ }}
    <span>wms</span>
    {{# }else if(d.serviceType == 4){ }}
    <span>wfs</span>
    {{# } }}
</script>
<script id="createTime-type" type="text/html">
    <div>{{ layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss') }}</div>
</script>
<script id="service-status" type="text/html">
    {{#if (d.status == 1) { }}
    <span style="color: #338528;">启用</span>
    {{# }else if(d.status == 0){ }}
    <span>禁用</span>
    {{# } }}
</script>



<script src="../../component/layui/layui.js"></script>
<script>
    var mapServerObj = {};
    
    layui.use(['table','form','jquery'],function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
     
        let MODULE_PATH = "/system/custom/";
        let cols = [
            [
                {type:'checkbox'},
                // {title: '缩略图', field: 'username', align:'center', width:100},
                {title: '要素名称', field: 'elementName',align:'center'  },
                {title: '要素描述', field: 'remark', edit:false, align:'center'},
                {title: '要素格式', field: 'serviceType', align:'center', templet:'#data-type'},
                {title: '服务地址', field: 'elementUrl', align:'center'},
                {title: '要素状态', field: 'status', sort: true,align:'center', templet:'#service-status'},
                {title: '创建时间', field: 'createTime', sort: true, align:'center',templet:'#createTime-type'},
                {title: '操作', toolbar: '#user-bar', fixed: 'right', align:'center', width:300}
            ]
        ]

        table.render({
            elem: '#user-table',
            url: '/one/element/origin/list',
            method: 'post',
            contentType: 'application/json',
            where: {
                order: 3,
                orderDesc: 0
            },
            request: {
                pageName: 'pageNo' //页码的参数名称，默认：page
                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            parseData: function(res){ //res 即为原始返回的数据
                console.log(154,$('.layui-table-tool-self'))
                // $('.layui-table-tool-self').children[0].title='刷新'
                if (res.errorCode === '401') {
                    loginStatusIntercept(res.msg)
                    return
                }else{
                    return {
                        "createTime": null,
                        "createBy": null,
                        "updateTime": null,
                        "updateBy": null,
                        "remark": null,
                        "code": 200,
                        "msg": "...",
                        "count": res.data.total,
                        "data":res.data.list
                    }
                }
            },
            id: 'user-table',
            page: true ,
            cols: cols ,
            skin: 'line',
            // even: true,//开启隔行背景
            toolbar: '#user-toolbar',
            initSort: {
                field: 'createTime',
                type: 'desc',
			},
            response: {
                statusCode: 200 //成功的状态码，默认：0
            },

            defaultToolbar: [{
                layEvent: 'refresh',
                icon: 'layui-icon-refresh',
                title:'刷新'
            }, 'filter']   //, 'print', 'exports'
        });
        function loginStatusIntercept(e){
            console.log(e);
            layer.msg(e);
            setTimeout(()=>{
                top.location.href = "/ftwgypt/login"
            },3000)
        }
        table.on('sort(user-table)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            // console.log(obj.field); //当前排序的字段名
            // console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）

            var field=obj.field;
            var type=obj.type;

            var order=1;
            var orderDesc=0;
            if(field==='createTime'){
                order=3;
            }else if(field==='updateTime'){
                order=2;
            }

            if(type==="asc"){
                orderDesc=1
            }else if(type=="desc"){
                orderDesc=0;
            }else{
                orderDesc=0;
                order=2;
            }


            //尽管我们的 table 自带排序功能，但并没有请求服务端。
            //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
            table.reload('user-table', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    order: order //排序字段   在接口作为参数字段  field order
                    ,orderDesc: orderDesc //排序方式   在接口作为参数字段  field order
                }
            });
        });
        table.on('tool(user-table)', function(obj){
            var data = obj.data;//获得当前行数据
            if(obj.event === 'detail'){
                // var pathname = top.location.href;
                // var JUMP_PATH = 'http://'+location.host+"/jump.html";
                var JUMP_PATH = window.sessionStorage.envLocation+"/jump.html";
                var url=data.elementUrl;
                var jumpUrl="";
                 // 判断添加的服务地址是否为geoserver发布的WFS服务
                if(url.indexOf("service=WFS") !== -1 ){

                    jumpUrl =  JUMP_PATH + '?url=' + data.elementUrl+'&type='+data.serviceType;//jumpUrl通过geoserver截断解决跨域问题
                    // jumpUrl =  JUMP_PATH + '?url=' +'http://192.168.2.108:9080/Proxy/proxyHandler?url='+ data.elementUrl+'&type='+data.serviceType;//jumpUrl通过geoserver截断解决跨域问题
                } else if(url.indexOf("service=WFS") === -1 ){
                    jumpUrl =  JUMP_PATH + '?url=' + data.elementUrl+'&type='+data.serviceType;//jumpUrl字符串中不含有service=WFS字符串
                }
                window.open(jumpUrl);
            } else if(obj.event === 'edit'){
                layer.open({
                    type: 1,
                    title: '修改地图服务要素',
                    shade: 0.1,//遮罩透明度
                    area: ['60%', '60%'],
                    content: $('#service-window'),
                    resize: true,
                    btn: ['确定', '取消'],
                    success:function(layero,index){
                        $('#feature-name').val(data.elementName);
                        $('#service-type').hide();
                        $('#service-address').hide();
                        $('#feature-detail').val(data.remark);
                    },
                    yes:function(index,layero){
                        if(!$('#feature-name').val()){
                            layer.msg("请输入要素名称", {icon: 5});
                            return;
                        }
                        $.ajax({
                            url: "/one/element/origin",
                            type: "PUT",
                            data:JSON.stringify({
                                elementName: $('#feature-name').val(),
                                remark: $('#feature-detail').val(),
                                id: data.id,
                            }),
                            dataType: "json",
                            contentType: "application/json; charset=UTF-8",
                            success: function(data){
                                if (data.errorCode === '401') {
                                    loginStatusIntercept(data.msg)
                                    return
                                }
                                if(data.success){
                                    layer.alert('修改成功',{icon:1,title:'提示'},function(i){
                                        layer.close(i);
                                        layer.close(index);//关闭弹出层
                                        $("#service-add")[0].reset()//重置form
                                    });
                                    table.reload('user-table',{//重载表格
                                        page:{
                                            curr:obj.curr
                                        }
                                    })
                                }else{
                                    layer.msg("修改失败,失败原因:"+data.msg, {icon: 5});
                                }
                            }
                        });
                    }
                });
            }else if(obj.event === 'del'){
                layer.confirm('确认删除？',{icon: 3, title:'提示'}, function(index){
                    let ids = data.id;
                    $.ajax({
                        url: "/one/element/originDel",
                        type: "POST",
                        data:{ids:ids},
                        dataType: "json",
                        success: function(data){
                            if (data.errorCode === '401') {
                                    loginStatusIntercept(data.msg)
                                    return
                                }
                            if(data.success){
                                //删除这一行
                                obj.del();
                                //关闭弹框
                                layer.close(index);
                                layer.msg("删除成功", {icon: 6});
                            }else{
                                layer.msg("删除失败", {icon: 5});
                            }
                        }
                    });
                });
            }

        });

        table.on('toolbar(user-table)', function(obj){
            if(obj.event === 'add'){
                mapServerObj.add();
            } else if(obj.event === 'refresh'){
                mapServerObj.refresh();
            } else if(obj.event === 'batchRemove'){
                mapServerObj.batchRemove(obj);
            } else if(obj.event === 'view'){
                mapServerObj.view(obj);
            }
        });

        $("#demoReload").unbind("keydown").keydown(function (e) {//当按下按键时
            e.stopPropagation()
            var key = e.keyCode || e.charCode || e.which;
            if (key == 13) {
                e.preventDefault()
                $("#featureSearch").trigger('click');
            }
        });
        $('#featureSearch').on('click', function(){
            var active = {
                reload: function(){
                    var demoReload = $('#demoReload');
                    console.log('fffff',demoReload.val());
                    //执行重载
                    table.reload('user-table', {
                        // url:'/one/element/origin/list',
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        // ,method: 'post'
                        ,where: {
                            elementName: demoReload.val()
                        }
                    }, 'data');
                }
            };
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        
        $('#featureReset').on('click', function(){
            console.log('rrrrr');
            var demoReload = $('#demoReload');
            demoReload.val("")
                    //执行重载
                    table.reload('user-table', {
                        // url:'/back/one/element/origin/list',
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        // ,method: 'post'
                        ,where: {
                            elementName: demoReload.val()
                        }
                    }, 'data');
        });


        form.on('switch(enabledState)', function(obj){
            //获取自定义标签valueId等上的值
            var switch_id = obj.elem.attributes['valueId'].nodeValue;
            var switch_ElementName = obj.elem.attributes['valueElementName'].nodeValue;
            var switch_ElementUrl = obj.elem.attributes['valueElementUrl'].nodeValue;
            var switch_ServiceType = obj.elem.attributes['valueServiceType'].nodeValue;
            // var switch_id = table.checkStatus('user-table');//表格id，获取选中行
            // var switch_id = obj.value;
            // layer.tips('温馨提示：'+ switch_ElementName + ' ' + this.name + '：'+ (this.checked ? '启用' : '禁用'), obj.othis);//更改操作后提示
            //开关是否开启，true或者false
            // var checked = obj.elem.checked;
            var validFlag = Number(obj.elem.checked);//转为 0、1
            console.log(validFlag);
            $.ajax({
                url: "/one/element/origin",
                type: "PUT",
                data:JSON.stringify({
                    id:switch_id,
                    elementName: switch_ElementName,
                    serviceType: switch_ServiceType,
                    elementUrl: switch_ElementUrl,
                    status: validFlag
                }),
                dataType: "json",
                contentType: "application/json; charset=UTF-8",
                success: function(data){
                    if (data.errorCode === '401') {
                                    loginStatusIntercept(data.msg)
                                    return
                                }
                    if(data.success){
                        table.reload('user-table');
                        // form.render();
                        form.render('checkbox');
                        console.log(obj.elem.checked);
                        // obj.elem.checked = !obj.elem.checked;
                        layer.msg('要素状态：'+ (obj.elem.checked ? '启用' : '禁用'), {
                            icon : 1
                        });
                        form.render('checkbox');
                        // form.render();
                    }else{
                        layer.msg("失败,失败原因:"+data.msg, {
                            icon : 2
                        });


                    }
                }

            });
            form.render('checkbox');
            // form.render();
        });
        //添加要素
        mapServerObj.add = function(data){
            layer.open({
                type: 1,
                title: '添加地图服务要素',
                shade: 0.1,
                area: ['70%', '70%'],
                content: $('#service-window'),
                resize: true,
                btn: ['确定', '取消'],
                success:function(layero,index){
                    $('#service-type').show();
                    $('#service-address').show();
                },
                yes:function(index,layero){
                    var url = $('#feature-address').val();
                    var reg=/(http|https):\/\/([\w.]+\/?)\S*/;
                    // var reg=/^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
                    var featureType = $("#feature-type").val();
                    if(!$('#feature-name').val()){
                        layer.msg("请输入要素名称", {icon: 5});
                        return;
                    }
                    else if(featureType === ''){
                        // alert(featureType);
                        layer.msg('请选择要素格式',{icon:2,time:1000});
                        return;
                    }
                    else if(!reg.test(url)){
                        layer.msg("这网址不是以http://https://开头，或者不是网址！", {icon: 5});
                        // layer.close(loading);
                        return;
                    }else{
                        $.ajax({
                            url: "/one/element/origin",
                            type: "POST",
                            data:JSON.stringify({
                                elementName: $('#feature-name').val(),
                                serviceType: $('#feature-type').val(),
                                elementUrl: $('#feature-address').val(),
                                remark: $('#feature-detail').val(),
                                status: 1
                            }),
                            dataType: "json",
                            contentType: "application/json; charset=UTF-8",
                            success: function(data){
                                if (data.errorCode === '401') {
                                    loginStatusIntercept(data.msg)
                                    return
                                }
                                if(data.success){
                                    layer.alert('增加成功',{icon:1,title:'提示'},function(i){
                                        layer.close(i);
                                        layer.close(index);//关闭弹出层
                                        $("#service-add")[0].reset()//重置form
                                    });
                                    table.reload('user-table',{//重载表格
                                        page:{
                                            curr:1
                                        }
                                    })
                                }else{
                                    layer.msg("添加失败,失败原因:"+data.msg, {icon: 5});
                                }
                            },
                            error:function (err) {
                                layer.msg("后台请求出错:"+err.responseText,{icon:2,time:1000});
                            }
                        });
                    }
                }
            });
        };
        mapServerObj.edit = function(obj){
            layer.open({
                type: 1,
                title: '修改',
                shade: 0.1,
                area: ['500px', '400px'],
                content: '<div style="padding: 20px 100px;">'+ 99 +'</div>'
            });
        };


        mapServerObj.view = function(obj){
            $.ajax({
                url: '/one/element/local/preview?id=10',
                dataType:'json',
                type:'get',
                success:function(result){
                    if (result.errorCode === '401') {
                        loginStatusIntercept(result.msg)
                        return
                    }
                    if(result.success){
                        layer.msg(result.msg,{icon:1,time:1000},function(){
                            // obj.del();
                        });
                    }else{
                        layer.msg(result.msg,{icon:2,time:1000});
                    }
                }
            })
        }

        mapServerObj.batchRemove = function(obj){
            let data = table.checkStatus(obj.config.id).data;
            if(data.length === 0){
                layer.msg("未选中数据",{icon:3,time:1000});
                return false;
            }
            let ids = "";
            for(let i = 0;i<data.length;i++){
                ids += data[i].id+",";
            }
            ids = ids.substr(0,ids.length-1);
            layer.confirm('确认删除该要素吗？', {icon: 3, title:'提示'}, function(index){
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: '/one/element/originDel',
                    dataType:'json',
                    type:'POST',
                    data:{ids:ids},
                    // data:JSON.parse(ids),
                    success:function(result){
                        layer.close(loading);
                        if (result.errorCode === '401') {
                            loginStatusIntercept(result.msg)
                            return
                        }
                        if(result.success){
                            layer.msg(result.msg,{icon:1,time:1000},function(){
                                table.reload('user-table');
                            });

                        }else{
                            layer.msg(result.msg,{icon:2,time:1000});
                        }
                    }
                })
            });
        }
        mapServerObj.refresh = function(param){
            table.reload('user-table');
        }
    })
</script>
</body>
</html>

